package com.example.util;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.mapp.ElevatorMapp;
import com.example.mapp.MessageNoticeMapp;
import com.example.mapp.PromotionMapp;
import com.example.mapp.StatisticsMapp;
import com.example.service.StatisticsService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by simon on 2017/10/3.
 */
@Component
@Configurable
@EnableScheduling
public class TaskUtil {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(TaskUtil.class);

	private static String appkey = "9e2d6b6f2387933a6983f7a5";

	private static String masterSecret = "d9c3da06f2102e5c3c02f207";

	@Autowired
	StatisticsService statisticsService;

	@Autowired
	private MessageNoticeMapp messageNoticeMapp;

	@Autowired
	private PromotionMapp promotionMapp;

	@Autowired
	private Environment environment;

	@Autowired
	StatisticsMapp statisticsMapp;
	
	@Autowired
    ElevatorMapp elevatorMapp;

	// @Scheduled(fixedRate = 1000 * 3)
	public void reportCurrentTime() {
		System.out.println("Scheduling Tasks Examples: The time is now " + (new Date()).getTime());
	}

	// 每1分钟执行一次
	// @Scheduled(cron = "0 */1 * * * * ")
	public void reportCurrentByCron() {
		System.out.println("Scheduling Tasks Examples By Cron: The time is now " + (new Date()).toString());
	}

	@Scheduled(cron = "0 0 7 * * ? ")
	public void pushNotice() {
//
//		boolean openstak = environment.getProperty("opentask",Boolean.class);
//		if(!openstak){
//			return;
//		}
		try {
			Map<String, Object> result = statisticsService.findNotice();
			if ((result.get("status")+"").equals("505")) {
				return;
			}
			List<Map<String, Object>> list = (List<Map<String, Object>>) result.get("data");
			String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			Set<String> maintSet = new HashSet<>();
			Set<String> yearMaintSet = new HashSet<>();

			for (Map<String, Object> tmp : list) {
				String statusId =  tmp.get("status_id")!=null?tmp.get("status_id")+"": "";
				String outsideNum =  tmp.get("outside_num")!=null?tmp.get("outside_num")+"": "";
				String safeUserId = tmp.get("safe_user_id")!=null?tmp.get("safe_user_id")+"": "";
				String usedPartyId =  tmp.get("used_party_id")!=null?tmp.get("used_party_id")+"": "";
				String elevatorStreet =  tmp.get("elevator_street")!=null?tmp.get("elevator_street")+"": "";
				String elevatorAddr = tmp.get("elevator_addr")!=null?tmp.get("elevator_addr")+"": "";
				String elevatorNum = tmp.get("elevator_num")!=null?tmp.get("elevator_num")+"": "";
				String maintDate = tmp.get("maint_date")!=null?tmp.get("maint_date")+"": "";
				String buildAddr = tmp.get("build_addr")!=null?tmp.get("maint_date")+"的": "";
				String content = buildAddr+"外部关联码为："+ outsideNum+" 的电梯," + "应于" + maintDate;
				String title = "";
				if (null == safeUserId || "".equals(safeUserId)) {
					continue;
				}
				if ("0".equals(statusId)) {
					title = "电梯将维保通知";
					content = content + "进行维保，请尽快处理。";
				} else if ("1".equals(statusId)) {
					title = "电梯维保过期通知";
					content = content + "进行维保，现已过期。";
					maintSet.add(elevatorNum);
				} else if ("3".equals(statusId)) { //年度定期检验
					title = "电梯将年检通知";
					content = content + "进行年检，请尽快处理。";
				} else if ("4".equals(statusId)) {
					title = "电梯年检超期通知";
					content = content + "进行定检，现已过期。";
					yearMaintSet.add(elevatorNum);
				}
				JpushUtil js = new JpushUtil(appkey, masterSecret, content, title);
				List<String> deviceIds = new ArrayList<>();
				if (null != tmp.get("register_id") && !tmp.get("register_id").equals("")) {
					deviceIds.add(tmp.get("register_id")+"");
				}
				if(deviceIds != null && deviceIds.size() > 0){
                    js.sendPushAll(true, deviceIds);
                }
				MessageNotice msg = new MessageNotice();
				msg.setTitle(title);
				msg.setContent(content);
				//msg.setSendUserId("");
				msg.setReceiveUserId(safeUserId);
				msg.setIsRead("0");
				msg.setNoticeTime(noticeTime);
				msg.setReceivePartyId(usedPartyId);
				messageNoticeMapp.add(msg);
			}
			
			for (String tmp : maintSet) {
				Elevator elevator = elevatorMapp.queryByElevatorNum(tmp);
				if (null != elevator.getMaintenancePartyId()) {
					PromotionUtil.calcParty(promotionMapp, -200, "1", elevator.getMaintenancePartyId(), "收到维保过期提示1条", "0");
				}
			}
			for (String tmp : yearMaintSet) {
				Elevator elevator = elevatorMapp.queryByElevatorNum(tmp);
				addEmpiric(elevator.getSafeUserId(), "3", -300, "收到电梯年检（定期检验）超期提示1条");
				if (null != elevator.getMaintenanceUserFirst()) {
					addEmpiric(elevator.getMaintenanceUserFirst(), "4", -300, "收到电梯年检（定期检验）超期提示1条");
				}
				if (null != elevator.getMaintenanceUserSecond()) {
					addEmpiric(elevator.getMaintenanceUserSecond(), "4", -300, "收到电梯年检（定期检验）超期提示1条");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
	}

	private void addEmpiric(Long userId, String type, Integer empiricValue, String content) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("type", type);
		Promotion promotion = promotionMapp.findById(map);
		if (null != promotion && promotion.getId() != null) {
			promotion = PromotionUtil.calc(promotion, type, empiricValue, false);
			promotionMapp.update(promotion);
		} else {
			promotion = new Promotion();
			promotion.setType(type);
			promotion.setUserId(userId.toString());
			promotion = PromotionUtil.calc(promotion, type, empiricValue, true);
			promotionMapp.insert(promotion);
		}
		PromotionRecord promotionRecord = new PromotionRecord();
		promotionRecord.setUserId(userId.toString());
		promotionRecord.setType(type);
		promotionRecord.setEmpiricItem(content);
		promotionRecord.setAddedTime(PromotionUtil.getTime());
		promotionRecord.setEmpiricValue(empiricValue);
		promotionMapp.insertRecord(promotionRecord);
	}
	
	@Scheduled(cron = "0 0 9 * * ? ")
	public void calcEmpiricValue() {
		boolean openstak = environment.getProperty("opentask",Boolean.class);
		if(!openstak){
			return;
		}
		try {
//			promotionMapp.deletePartyAddedScore();
//			promotionMapp.insertPartyAddedScore();
//			String month = new SimpleDateFormat("yyyyMM").format(new Date());
//			promotionMapp.updatePartyAdded2(month);
//			promotionMapp.insertPartyAdded2(month);
//			promotionMapp.insertPartyAdded3();
//			promotionMapp.updatePartyAddedScore();
			promotionMapp.deleteSecurityTipRecord();
			
			List<ElevatorAppraisal> list = promotionMapp.findFeedbakOvertime();
			for (ElevatorAppraisal tmp : list) {
				if ("1".equals(tmp.getIsFeedBack())) {
	            	Elevator elevator = elevatorMapp.queryById(tmp.getElevatorId());
					if (null != elevator && null != elevator.getSafeUserId()) {
						Map<String, Object> map = new HashMap<>();
						map.put("type", "3");
						map.put("userId", elevator.getSafeUserId());
						Promotion promotion = promotionMapp.findById(map);
						if (null != promotion && promotion.getId() != null) {
							promotion = PromotionUtil.calc(promotion, "3", -30, false);
							promotionMapp.update(promotion);
						} else {
							promotion = new Promotion();
							promotion.setType("3");
							promotion.setUserId(elevator.getSafeUserId().toString());
							promotion = PromotionUtil.calc(promotion, "3", -30, true);
							promotionMapp.insert(promotion);
						}
						PromotionRecord promotionRecord = new PromotionRecord();
						promotionRecord.setUserId(promotion.getUserId());
						promotionRecord.setType(promotion.getType());
						promotionRecord.setEmpiricItem("超过7日仍未回复乘客评价（包括点赞和反馈）");
						promotionRecord.setAddedTime(PromotionUtil.getTime());
						promotionRecord.setEmpiricValue(-30);
						promotionMapp.insertRecord(promotionRecord);
					}
	            }
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
	}

//	@Scheduled(cron = "0 0 0 1 * ? ")
	public void rewardNotice() {
		boolean openstak = environment.getProperty("opentask",Boolean.class);
		if(!openstak){
			return;
		}
		try {
			String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String month = PromotionUtil.getLastMonth();
			String month2 = month.substring(0, 4) + "年" + month.substring(4, 6) + "月";
			String title = month2 + "维保单位排行第一名";
			Map<String, Object> map1 = promotionMapp.findRankingPartyOne("1");
			String content = month2 + "排行第一名的维保单位如下：" + map1.get("content") + "，请颁发广告位奖励。";
			MessageNotice msg1 = new MessageNotice();
			msg1.setTitle(title);
			msg1.setContent(content);
			//msg.setSendUserId("");
			msg1.setReceiveUserId("admin");
			msg1.setIsRead("0");
			msg1.setNoticeTime(noticeTime);
			msg1.setReceivePartyId("1");
			messageNoticeMapp.add(msg1);

			title = month2 + "物业单位排行第一名";
			Map<String, Object> map2 = promotionMapp.findRankingPartyOne("2");
			content = month2 + "排行第一名的物业单位如下：" + map2.get("content") + "，请颁发广告位奖励。";
			MessageNotice msg2 = new MessageNotice();
			msg2.setTitle(title);
			msg2.setContent(content);
			//msg.setSendUserId("");
			msg2.setReceiveUserId("admin");
			msg2.setIsRead("0");
			msg2.setNoticeTime(noticeTime);
			msg2.setReceivePartyId("1");
			messageNoticeMapp.add(msg2);

			title = month2 + "维保单位加分前三名";
			Map<String, Object> param1 = new HashMap<>();
			param1.put("month", month);
			param1.put("type", "1");
			Map<String, Object> map3 = promotionMapp.findRankingAddedThree(param1);
			content = month2 + "加分前三名的维保单位如下：" + map3.get("content") + "，请设置为维保推荐单位。";
			MessageNotice msg3 = new MessageNotice();
			msg3.setTitle(title);
			msg3.setContent(content);
			//msg.setSendUserId("");
			msg3.setReceiveUserId("admin");
			msg3.setIsRead("0");
			msg3.setNoticeTime(noticeTime);
			msg3.setReceivePartyId("1");
			messageNoticeMapp.add(msg3);

			title = month2 + "物业单位加分前三名";
			Map<String, Object> param2 = new HashMap<>();
			param2.put("month", month);
			param2.put("type", "2");
			Map<String, Object> map4 = promotionMapp.findRankingAddedThree(param2);
			content = month2 + "加分前三名的物业单位如下：" + map4.get("content") + "，请设置为物业推荐单位。";
			MessageNotice msg4 = new MessageNotice();
			msg4.setTitle(title);
			msg4.setContent(content);
			//msg.setSendUserId("");
			msg4.setReceiveUserId("admin");
			msg4.setIsRead("0");
			msg4.setNoticeTime(noticeTime);
			msg4.setReceivePartyId("1");
			messageNoticeMapp.add(msg4);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
	}

	
	@Scheduled(cron = "0 0 0 1 1/3 ? ")
	public void quarterStatistics() {
		boolean openstak = environment.getProperty("opentask",Boolean.class);
		if(!openstak){
			return;
		}
		try {
			statisticsMapp.insertImplementation();
			statisticsMapp.insertRepair();
			statisticsMapp.insertMaintOvertime();
			statisticsMapp.insertCheckOvertime2();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
	}
}
